package com.liangxy.zhyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.liangxy.zhyl.constant.Constants;
import com.liangxy.zhyl.dto.UserLoginRequestDto;
import com.liangxy.zhyl.entity.Member;
import com.liangxy.zhyl.mapper.MemberMapper;
import com.liangxy.zhyl.properties.JwtTokenManagerProperties;
import com.liangxy.zhyl.service.MemberService;
import com.liangxy.zhyl.service.WechatService;
import com.liangxy.zhyl.utils.JwtUtil;
import com.liangxy.zhyl.utils.StringUtils;
import com.liangxy.zhyl.vo.LoginVo;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );



    /**
     * 小程序登录逻辑
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1. 调用微信api,根据code获取openId
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());
        // 2. 根据openId查询用户
        Member member = memberMapper.getByOpenId(openId);
        // 3. 如果用户不存在,则新增用户
        if (member == null) {
            member = Member.builder()
                    .openId(openId)
                    .build();
        }
        // 4. 调用微信api,获取用户绑定的手机号--目的是能够随时更新用户的手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        // 5. 保存或修改用户
        saveOrUpdate(member, phone);
        // 6. 用户id存入token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    /**
     * 保存或修改用户
     * @param member
     * @param phone
     */
    private void saveOrUpdate(Member member, String phone) {
        // 1. 判断取到的手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(phone,member.getPhone())){
            member.setPhone(phone);
        }
        // 2. 判断用户是否存在
        if(ObjectUtil.isNull(member.getOpenId())){
            memberMapper.update(member);
            return;
        }
        // 3. 保存新用户
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int)Math.random()*DEFAULT_NICKNAME_PREFIX.size())
                + StringUtils.substring(member.getPhone(),7);
        member.setName(nickName);
        memberMapper.save(member);
    }
}
